#define _CRT_SECURE_NO_WARNINGS

#include"SList.h"

void SListInit(SLTNode*ps)
{
	ps->val = 0;
	ps->next = NULL;
}

void SListPrint(SLTNode* phead)
{
	SLTNode* cur = phead;
	if (phead == NULL)
	{
		printf("NULL");
		return;
	}
	while (cur)
	{
		printf("%d->",cur->val);
		cur = cur->next;
	}
	printf("NULL");
}

void SListPushBack(SLTNode** phead, SLTDateType x)
{
	SLTNode* newnode = (SLTNode*)malloc(sizeof(SLTNode));
	SLTNode* cur = *phead;
	SLTNode* prev = *phead;
	if (*phead == NULL)
	{
		*phead = newnode;
		newnode->next = NULL;
		newnode->val = x;
	}
	else
	{
		while (cur)
		{
			prev = cur;
			cur = cur->next;
		}
		newnode->val = x;
		prev->next = newnode;
		newnode->next = NULL;
	}
}

void SListPushFront(SLTNode** phead, SLTDateType x)
{
	SLTNode* newnode= (SLTNode*)malloc(sizeof(SLTNode));
	if (*phead == NULL)
	{
		*phead = newnode;
		newnode->next = NULL;
		newnode->val = x;
	}
	else
	{
		SLTNode* cur = *phead;
		*phead = newnode;
		newnode->next = cur;
		newnode->val = x;
	}
}

void SListPopBack(SLTNode** phead)
{
	assert(*phead!=NULL);
	SLTNode* prev = *phead;
	SLTNode* cur = *phead;
	while (cur->next)
	{
		prev = cur;
		cur = cur->next;
	}
	if (cur == *phead)
	{
		free(cur);
		*phead = NULL;
		return;
	}
	prev->next = NULL;
	free(cur);
}

void SListPopFront(SLTNode** phead)
{
	assert(*phead != NULL);
	SLTNode* cur = (*phead)->next;
	free(*phead);
	*phead = cur;
}

SLTNode* SListFind(SLTNode* phead, SLTDateType x)
{
	if (phead == NULL)
		return NULL;
	else
	{
		SLTNode* cur = phead;
		while (cur)
		{
			if (cur->val == x)
			{
				return cur;
			}
			else
			{
				cur = cur->next;
			}
		}
		return NULL;
	}
}

void SListInsert(SLTNode** phead, SLTNode* pos, SLTDateType x)
{
	assert(pos != NULL);
	SLTNode* newnode = (SLTNode*)malloc(sizeof(SLTNode));
	SLTNode* cur = *phead;
	if (pos == *phead)
	{
		cur = *phead;
		*phead = newnode;
		newnode->next = cur;
		newnode->val = x;
	}
	else
	{
		SLTNode* prev = *phead;
		while (cur)
		{
			if (cur == pos)
			{
				prev->next = newnode;
				newnode->next = cur;
				newnode->val = x;
				return;
			}
			prev = cur;
			cur = cur->next;
		}
	}
}


void SListEase(SLTNode** phead, SLTNode* pos)
{
	assert(*phead != NULL);
	assert(pos != NULL);
	SLTNode* next = pos->next;
	SLTNode* cur = *phead;
	if (pos == *phead)
	{
		cur = (*phead)->next;
		free(*phead);
		*phead = cur;
		return;
	}
	while (cur)
	{
		if (cur->next == pos)
		{
			cur->next = next;
			free(pos);
		}
		cur = cur->next;
	}
}

void SListDestory(SLTNode** phead)
{
	SLTNode* cur = *phead;
	SLTNode* next = (*phead)->next;
	*phead = NULL;
	while (cur)
	{
		next = cur->next;
		free(cur);
		cur = next;
	}
}